/**
 * @Copyright:Copyright (c) 2007 - 2023
 * 
 */
package com.tengtong.commons.lang;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.function.Consumer;

/**
 * 数组的工具
 *
 * @author lin_jinming
 * @since: v1.0
 */
public class ArrayUtils {

    /**
     * 判断数组是否为空
     *
     * @param os
     * @return
     */
    public final static boolean isEmpty(Object[] os) {
        return os == null || os.length <= 0;
    }
    
    public final static boolean notEmpty(Object[] os) {
        return !notEmpty(os);
    }
    
    /**
     * 将一个对象转为数组，如果无法转就抛出异常
     *
     * @param source
     * @return
     */
    public static Object[] toObjectArray(Object source) {
        if (source instanceof Object[]) {
            return (Object[]) source;
        }
        if (source == null) {
            return new Object[0];
        }
        if (!source.getClass().isArray()) {
            throw new IllegalArgumentException("Source is not an array: " + source);
        }
        int length = Array.getLength(source);
        if (length == 0) {
            return new Object[0];
        }
        Class<?> wrapperType = Array.get(source, 0).getClass();
        Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
        for (int i = 0; i < length; i++) {
            newArray[i] = Array.get(source, i);
        }
        return newArray;
    }
    
    /**
     * 将 source 转换为数组，然后进行遍历。如果 source 无法转成数组，则将作为 Object[]{source} 使用
     *
     * @param source
     * @param consumer
     */
    public static void eachArray(Object source, Consumer<Object> consumer) {
        Object[] arrays = null;
        try {
            arrays = toObjectArray(source);
        }
        catch (Exception e) {
            arrays = new Object[] {source};
        }
        Arrays.stream(arrays)
              .forEach(consumer);
    }
}
